
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.PrintStream;
import java.net.DatagramPacket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Arthur
 */
public class Chat extends javax.swing.JFrame {

    /**
     * Creates new form Chat
     *
     * @param login
     * @param nickname
     */
    private String nickname;
    private Socket conexao;
    private PrintStream saida;
    private final DefaultListModel modelListaMensagens = new DefaultListModel();
    private final DefaultListModel modelListaUsuarios = new DefaultListModel();
    private ArrayList<ChatPrivado> listaChats = new ArrayList<ChatPrivado>();
    private Recebedor recebedor;
    private ArrayList<String> listaConvites = new ArrayList<String>();

    public Chat(Login login, Socket conexao, String nickname) throws IOException, InterruptedException {
        initComponents();
        login.setVisible(false);
        this.setLocationRelativeTo(null);
        this.conexao = conexao;
        this.nickname = nickname;
        saida = new PrintStream(conexao.getOutputStream());
        listaMensagens.setModel(modelListaMensagens);
        listaUsuarios.setModel(modelListaUsuarios);
        recebedor = new Recebedor(conexao, listaMensagens, modelListaMensagens, modelListaUsuarios, this, login, nickname);
        Thread thread = recebedor;
        thread.start();
    }

    public Chat() {
    }

    public Chat(Socket conexao, String nickname, DefaultListModel lista) throws IOException {
        initComponents();
        Login login = new Login();
        this.setLocationRelativeTo(null);
        this.conexao = conexao;
        this.nickname = nickname;
        saida = new PrintStream(conexao.getOutputStream());
        listaMensagens.setModel(lista);
        listaUsuarios.setModel(modelListaUsuarios);
        recebedor = new Recebedor(conexao, listaMensagens, lista, modelListaUsuarios, this, login, nickname);
        Thread thread = recebedor;
        thread.start();
    }

    public ArrayList<ChatPrivado> getListaChats() {
        return listaChats;
    }

    public void setListaChats(ArrayList<ChatPrivado> listaChats) {
        this.listaChats = listaChats;
    }

    public ArrayList<String> getListaConvites() {
        return listaConvites;
    }

    public void setListaConvites(ArrayList<String> listaConvites) {
        this.listaConvites = listaConvites;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        mensagem = new javax.swing.JTextArea();
        botaoEnviar = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        listaMensagens = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        listaUsuarios = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        botaoSair = new javax.swing.JButton();
        checkTeclaEnter = new javax.swing.JCheckBox();
        checkSom = new javax.swing.JCheckBox();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Chat");

        mensagem.setColumns(20);
        mensagem.setFont(new java.awt.Font("Arial Rounded MT Bold", 0, 13)); // NOI18N
        mensagem.setRows(5);
        mensagem.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                mensagemKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(mensagem);

        botaoEnviar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/enviar.png"))); // NOI18N
        botaoEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoEnviarActionPerformed(evt);
            }
        });

        listaMensagens.setFont(new java.awt.Font("Arial Rounded MT Bold", 0, 11)); // NOI18N
        listaMensagens.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        listaMensagens.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listaMensagensMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(listaMensagens);

        listaUsuarios.setFont(new java.awt.Font("Arial Rounded MT Bold", 0, 11)); // NOI18N
        listaUsuarios.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listaUsuariosMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(listaUsuarios);

        jLabel1.setFont(new java.awt.Font("Geometr415 Blk BT", 0, 14)); // NOI18N
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/users.png"))); // NOI18N
        jLabel1.setText("Usuários on-line");

        botaoSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/sair.png"))); // NOI18N
        botaoSair.setText("Sair");
        botaoSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoSairActionPerformed(evt);
            }
        });

        checkTeclaEnter.setText("Desativar envio com a tecla Enter");

        checkSom.setText("Desativar sons");
        checkSom.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                checkSomMouseClicked(evt);
            }
        });

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/Superior.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)
                            .addComponent(jScrollPane3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(botaoSair, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(botaoEnviar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(162, 162, 162)
                                .addComponent(jLabel2))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(checkTeclaEnter)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(checkSom)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {botaoEnviar, botaoSair, jLabel1, jScrollPane2});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(botaoEnviar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(checkTeclaEnter)
                    .addComponent(checkSom)
                    .addComponent(botaoSair))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {botaoSair, checkSom, checkTeclaEnter});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botaoSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoSairActionPerformed
        if (listaChats.isEmpty()) {
            saida.println(""); //remove do chat
            System.exit(0);
        } else {
            int answer = JOptionPane.showConfirmDialog(null, "Você possui conversa privada aberta e se sair ela também será fechada. Deseja mesmo sair?");
            if (answer == JOptionPane.YES_OPTION) {
                for (ChatPrivado listaChat : listaChats) {
                    saida.println("6_%&" + listaChat.getNickname());
                }
                saida.println(""); //remove do chat
                System.exit(0);
            } else {

            }
        }
    }//GEN-LAST:event_botaoSairActionPerformed

    private void botaoEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoEnviarActionPerformed

        if (!mensagem.getText().trim().equals("")) {
            if (mensagem.getText().contains("&")) {
                JOptionPane.showMessageDialog(null, "Sua mensagem não foi enviada pois contém caracteres proibidos.");
            } else {
                saida.println(mensagem.getText());
                mensagem.setText("");
            }
        }
    }//GEN-LAST:event_botaoEnviarActionPerformed

    private void mensagemKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_mensagemKeyPressed

        int key = evt.getKeyCode();
        if (!checkTeclaEnter.isSelected()) {
            if (key == KeyEvent.VK_ENTER) {
                if (mensagem.getText().contains("&")) {
                    JOptionPane.showMessageDialog(null, "Sua mensagem não foi enviada pois contém caracteres proibidos.");
                } else {
                    if (!mensagem.getText().trim().equals("")) {
                        String a = mensagem.getText();
                        saida.println(mensagem.getText().trim());
                        mensagem.setText(null);
                    }
                }
            }
        }
    }//GEN-LAST:event_mensagemKeyPressed

    private void listaMensagensMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listaMensagensMouseClicked


    }//GEN-LAST:event_listaMensagensMouseClicked

    private void listaUsuariosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listaUsuariosMouseClicked
        // TODO add your handling code here:
        if (evt.getClickCount() == 2) {
            int index = listaUsuarios.locationToIndex(evt.getPoint());
            boolean aux = false;
            if (!nickname.toUpperCase().equals(modelListaUsuarios.getElementAt(index)) && index >= 0) {
                for (ChatPrivado listaChat : listaChats) {
                    if (listaChat.getNickname().equals(modelListaUsuarios.getElementAt(index))) {
                        aux = true;
                        JOptionPane.showMessageDialog(null, "Você já está em uma conversa privada com esta pessoa.");
                        break;
                    }
                }
                if (listaConvites.contains(modelListaUsuarios.getElementAt(index).toString())) {
                    aux = true;
                    JOptionPane.showMessageDialog(null, "Você já convidou esta pessoa para uma conversa privada. Aguarde a resposta.");
                }
                if (!aux) {
                    int answer = JOptionPane.showConfirmDialog(null, "Deseja convidar " + modelListaUsuarios.getElementAt(index) + " para uma conversa privada?");
                    if (answer == JOptionPane.YES_OPTION) {
                        listaConvites.add(modelListaUsuarios.getElementAt(index).toString());
                        modelListaMensagens.add(modelListaMensagens.size(), horaAtual() + "Você convidou " + modelListaUsuarios.getElementAt(index) + " para uma conversa privada. Aguarde a resposta.");
                        saida.println("3_" + nickname + "&" + modelListaUsuarios.getElementAt(index));
                    }
                }
            }
        }
    }//GEN-LAST:event_listaUsuariosMouseClicked

    private void checkSomMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_checkSomMouseClicked
        // TODO add your handling code here:
        if (checkSom.isSelected()) {
            recebedor.setCheckboxSom(true);
        } else {
            recebedor.setCheckboxSom(false);
        }
    }//GEN-LAST:event_checkSomMouseClicked

    public String horaAtual() {
        String formatoHora = "HH:mm:ss";
        Date agora = new Date();
        SimpleDateFormat formata = new SimpleDateFormat(formatoHora);
        return "[" + formata.format(agora) + "] ";
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Chat().setVisible(true);
            }
        });
    }

    static void stringToPacket(String s, DatagramPacket packet) {
        byte[] bytes = s.getBytes();
        System.arraycopy(bytes, 0, packet.getData(), 0, bytes.length);
        packet.setLength(bytes.length);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoEnviar;
    private javax.swing.JButton botaoSair;
    private javax.swing.JCheckBox checkSom;
    private javax.swing.JCheckBox checkTeclaEnter;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JList listaMensagens;
    private javax.swing.JList listaUsuarios;
    private javax.swing.JTextArea mensagem;
    // End of variables declaration//GEN-END:variables
}
